# -*- coding: utf-8 -*-
from itertools import count
from QuModLibs.Server import *


class BlockDestroyer:
    
    def __init__(self):
        self.block_player = []
        self.play_config = {}
        self.play_open={}
        # ListenForEvent("ServerPlayerTryDestroyBlockEvent", self,self.OnServerPlayerTryDestroyBlockEvent)
        print("Start")
    def open_listen(self):
        print("open_listen")
        ListenForEvent("ServerPlayerTryDestroyBlockEvent", self,self.OnServerPlayerTryDestroyBlockEvent)
    def close_listen(self):
        UnListenForEvent("ServerPlayerTryDestroyBlockEvent", self,self.OnServerPlayerTryDestroyBlockEvent)
    
    def OnServerPlayerTryDestroyBlockEvent(self, event):
        data = {
            "x": event["x"],
            "y": event["y"],
            "z": event["z"],
            "playerId": event["playerId"],
            "fullName": event["fullName"],
            "dimensionId": event["dimensionId"],
        }
        if data["playerId"] not in self.block_player:
            self.block_player.append(data["playerId"])
            self.destroy(data)
            self.block_player.remove(data["playerId"])
        
    def destroy(self, data):
        if data["playerId"] not in self.play_open or not self.play_open[data["playerId"]]:
            return
        x = data["x"]
        y = data["y"]
        z = data["z"]
        playerId = data["playerId"]
        fullName = data["fullName"]
        dimensionId = data["dimensionId"]
        
        # 获取玩家设置的挖掘上限，默认为64
        max_count = 64
        if playerId in self.play_config and "chain_max" in self.play_config[playerId]:
            try:
                max_count = int(self.play_config[playerId]["chain_max"])
            except ValueError:
                pass
        
        block_break = self.select_block((x,y,z),fullName,dimensionId, max_count)
        comp = serverApi.GetEngineCompFactory().CreateBlockInfo(playerId)  # 此处playerId为block的破坏者
        print(1)
        if block_break:
            for block_pos in block_break:
                comp.PlayerDestoryBlock(block_pos, 1, False)
        
    def select_block(self, pos, fullName, dimensionId, max_count):
        block_break = []
        visited = set()
        
        def dfs(current_pos):
            # 如果已达到挖掘上限，停止递归
            if len(block_break) >= max_count:
                return
            
            # 如果已经访问过，停止递归
            if current_pos in visited:
                return
            
            # 标记为已访问
            visited.add(current_pos)
            
            comp = serverApi.GetEngineCompFactory().CreateBlockInfo(dimensionId)
            blockDict = comp.GetBlockNew(current_pos, dimensionId)
            blockName = blockDict["name"]
            
            # 如果是目标方块，添加到结果列表
            if blockName == fullName:
                block_break.append(current_pos)
                
                # 继续向周围8个方向搜索
                for dx in [-1, 0, 1]:
                    for dy in [-1, 0, 1]:
                        for dz in [-1, 0, 1]:
                            # 跳过自己
                            if dx == 0 and dy == 0 and dz == 0:
                                continue
                            new_pos = (current_pos[0] + dx, current_pos[1] + dy, current_pos[2] + dz)
                            dfs(new_pos)
        
        # 从起始位置开始DFS
        dfs(pos)
        
        # 移除起始位置（玩家手动破坏的方块）
        if pos in block_break:
            block_break.remove(pos)
        
        return block_break

block_destroyer = BlockDestroyer()
block_destroyer.open_listen()

@AllowCall
def Call_A(data):
    block_destroyer.play_config[data["playerId"]] = data
    pass
@AllowCall
def Call_B(data):
    block_destroyer.play_open[data["playerId"]] = data["open"]
    pass